/**
 * Created by baiguiren on 2/14/17.
 */

let params = function (req, res, next) {
  let multiparty = require('multiparty');
  req._params = {}; //不能使用global.params, global是常驻内存的, 会导致全局污染, req会在请求结束后清空

  if (req.is('multipart/form-data')) {
    //使用multiparty提取参数
    let form = new multiparty.Form();
    form.on('field', function (name, value) {
      //global.params.name = value;
      //错误, 这样其实是设置global.params的name属性, 而不是name对应的字符串,
      //如传入'age', 23的时候, 实际上是执行了global.params.name = 23, 而不是global.params.age = 23;
      req._params[name]= value;
    });
    form.on('file', function (name, value) {
      req._params[name]= value;
    });
    form.parse(req, function (err, fields, files) {
      if (err) {
        res.end(err.toString());
        return;
      }
      //console.log(req._params);
      next();
    });
  } else {
    Object.assign(req._params, req.query);
    Object.assign(req._params, req.body);
    next();
  }
};

exports = module.exports = params;